import {getInfo, login, logout} from "@/api/system/loginApi";
import defAva from '@/assets/img/profile.jpg'
import cacheUtil from "@/utils/cacheUtil";

const useUserStore = defineStore('user-store',{
    state: ()=>({
        userInfo: cacheUtil.session.get('userInfo'),
        avatar: '',
        token: cacheUtil.session.get('token'),
        roles: [],
        permissions: [],
    }),
    actions: {
        login(userInfo){
            return new Promise((resolve, reject) => {
                login(userInfo).then(res =>{
                    const data = res.data || {};
                    this.token = data.tokenValue;
                    cacheUtil.session.set('token',data.tokenValue)
                    resolve(res);
                }).catch(err =>{
                    reject(err);
                })
            })
        },
        getInfo(){
            return new Promise((resolve, reject)=> {
                getInfo().then(res => {
                    const user = res.data
                    const avatar = (user.avatar === "" || user.avatar == null) ? defAva : user.avatar;

                    if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        this.roles = res.data.roles
                        this.permissions = res.data.permissions
                    } else {
                        this.roles = ['ROLE_DEFAULT']
                    }
                    this.avatar = avatar
                    user['avatar'] = avatar;
                    this.userInfo = user
                    cacheUtil.session.set('userInfo',user)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        logOut(){
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    // 清除会话信息
                    this.clearLogin()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        clearLogin(){
            this.token = ''
            this.roles = []
            this.permissions = []
            this.userInfo = {}
            cacheUtil.session.clear();
        }
    }
})

export default useUserStore;
